//
//  ForgetPasswordFromViewController.m
//  Gxj
//
//  Created by 刘伟 on 2017/9/16.
//  Copyright © 2017年 wkq. All rights reserved.
//

#import "ForgetPasswordFromViewController.h"
#import "ForgetPasswordFromView.h"

@interface ForgetPasswordFromViewController ()<UITextFieldDelegate>
{
    ForgetPasswordFromView *_forgetPassWordView;
    int timeTick;
    NSTimer* timer;
}

@end

@implementation ForgetPasswordFromViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"忘记密码";
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bg"]forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = YES; // 设置导航背景图片之后发生偏移，使用此属性回归正常
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:17]};
    
    _forgetPassWordView = [[ForgetPasswordFromView alloc] init];
    _forgetPassWordView.userNum.delegate = self;
    _forgetPassWordView.userPassWord.delegate = self;
    _forgetPassWordView.verification.delegate = self;
    _forgetPassWordView.confirmPassword.delegate = self;
    
    
    [_forgetPassWordView.sendVerification addTarget:self action:@selector(ForgetPasswordSendVerification:) forControlEvents:UIControlEventTouchUpInside];
    [_forgetPassWordView.commit addTarget:self action:@selector(ForgetPasswordCommit:) forControlEvents:UIControlEventTouchUpInside];
    
    self.view = _forgetPassWordView;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 300000) {
        if (range.location >= 11){
            return NO; // return NO to not change text
        }
    }else if (textField.tag == 300001){
        if (range.location >= 6) {
            return NO;
        }
    }else if (textField.tag == 300002){
        if (range.location >= 13) {
            return NO;
        }
    }else if (textField.tag == 300003){
        if (range.location >= 13) {
            return NO;
        }
    }
    
    return YES;
}

- (void)ForgetPasswordCommit:(UIButton *)sender
{
    if (![_forgetPassWordView.userNum.text isEqualToString:@""] && ![_forgetPassWordView.verification.text isEqualToString:@""] && ![_forgetPassWordView.userPassWord.text isEqualToString:@""]) {
        
        if ([_forgetPassWordView.userPassWord.text isEqualToString:[NSString stringWithFormat:@"%@",_forgetPassWordView.confirmPassword.text]]) {
    
            NSDictionary *dicc = @{@"username":_forgetPassWordView.userNum.text,
                                   @"smscode" :_forgetPassWordView.verification.text,
                                   @"password":_forgetPassWordView.userPassWord.text
                                   };
            
            [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/index/findpassword",MAIN_URL] parameters:dicc success:^(NSDictionary *dic) {
                
                NSLog(@"forgetPassword:%@",dic);
                
                BOOL resstate = [dic objectForKey:@"resstate"];
                if (resstate == true) {
                    
                    [KQUserDefaults removeUserDataWithkey:@"userPassword"];
                    [KQUserDefaults writeUserDataWithKey:_forgetPassWordView.userPassWord.text forKey:@"userPassword"];
                    
                    [SVProgressHUD showSuccessWithStatus:[dic objectForKey:@"msg"]];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                
                else{
                    [SVProgressHUD showErrorWithStatus:[dic objectForKey:@"msg"]];
                }
            } failure:^(NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"网络异常~\(≧▽≦)/~啦啦啦"];
            }];
        }else{
            [TTAlertView alertViewWithTitle:@"温馨提示" Message:@"您两次输入密码不一致" cancelBtnTitle:nil sureBtnTitle:@"确定" sureBtnClick:^{
                
            } cancelBtnClick:^{
                
            }];
        }
    }else{
        [TTAlertView alertViewWithTitle:@"温馨提示" Message:@"您输入的信息不完整" cancelBtnTitle:nil sureBtnTitle:@"确定" sureBtnClick:^{
            
        } cancelBtnClick:^{
            
        }];
    }

}

// 获取验证码
- (void)ForgetPasswordSendVerification:(UIButton *)sender
{
    BOOL isPhoneNumber = [Regula isMobilePhoneNumber:_forgetPassWordView.userNum.text];
    
    if (isPhoneNumber == YES) {
        
        NSDictionary *dicc = @{@"username":_forgetPassWordView.userNum.text
                               };
        
        [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/index/sendpwdsms",MAIN_URL] parameters:dicc success:^(NSDictionary *dic) {
            NSLog(@"sendVerification :%@",dic);
            BOOL resstate = [dic objectForKey:@"resstate"];
            if (resstate == true) {
                // 发送成功
                [SVProgressHUD showSuccessWithStatus:[dic objectForKey:@"msg"]];
                timeTick =  60;
                timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
            }
            
            else{
                [SVProgressHUD showErrorWithStatus:[dic objectForKey:@"msg"]];
            }
            
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络异常~\(≧▽≦)/~啦啦啦"];
        }];
    }
    else{
        [TTAlertView alertViewWithTitle:@"获取验证码失败" Message:@"请输入正确的手机号" cancelBtnTitle:nil sureBtnTitle:@"确定" sureBtnClick:^{
            
        } cancelBtnClick:^{
            
        }];
    }
}

// 验证码倒计时
-(void)timeFireMethod
{
    timeTick--;
    if(timeTick==0){
        
        _forgetPassWordView.sendVerification.enabled=YES;
        [timer invalidate];
        [_forgetPassWordView.sendVerification setTitle:@"获取验证码" forState:0];
    }else
    {
        [_forgetPassWordView.sendVerification setTitle:[NSString stringWithFormat:@"%ds后重新获取",timeTick] forState:0];
        _forgetPassWordView.sendVerification.titleLabel.font = [UIFont systemFontOfSize:kWidthScale(13)];
        [_forgetPassWordView.sendVerification setTitleColor:[UIColor whiteColor] forState:0];
        _forgetPassWordView.sendVerification.enabled = NO;
    }
}

#pragma mark - 点击空白回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
